package com.cqjtu.education.controller;

import cn.dev33.satoken.annotation.SaCheckRole;
import cn.dev33.satoken.stp.StpUtil;
import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.cqjtu.education.entity.User;
import com.cqjtu.education.service.UserService;
import com.cqjtu.education.utils.*;
import com.google.gson.Gson;
import darabonba.core.client.ClientOverrideConfiguration;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;


/**
 * (User)表控制层
 *
 * @author makejava
 * @since 2022-04-07 13:57:18
 */
@Api(tags = "用户相关接口")
@RestController
@RequestMapping("user")
@Slf4j
public class UserController {
    /**
     * 服务对象
     */
    @Resource
    private UserService userService;

    @Resource
    private AliyunOSS aliyunOSS;

    @Resource
    private RedisUtils redisUtils;

    @Resource
    private CodeUtil codeUtil;

    @Resource
    private EmailUtil emailUtil;


    @ApiOperation(value = "uploadUserImage", notes = "上传用户头像")
    @RequestMapping("/uploadUserImage")
    public Result uploadUserImage(String id, MultipartFile file) {
        if (file == null) {
            return Result.fail("文件为空");
        }
        try {
            return Result.success(userService.uploadUserImage(id, file));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.fail("操作失败");
    }

    @ApiOperation(value = "resetPassword", notes = "重置密码，key为手机号，code为验证码，password为新密码")
    @RequestMapping("/resetPassword")
    public Result resetPassword(String key, String code, String password) {
        if (!userService.isRegister(key)) {
            return Result.fail("该手机号未注册，请先注册");
        }
        boolean hasKey = redisUtils.exists(key);
        if (hasKey) {
            Object object = redisUtils.get(key);
            if (code.equals(object.toString())) {
                userService.changePassword(userService.queryByTel(key).getId(), password);
                return Result.success("重置成功");
            } else {
                return Result.fail("验证码不匹配");
            }
        } else {
            return Result.fail("请注意是否发送短信验证码或验证码已过期");
        }
    }

    /**
     * 获取验证码
     *
     * @param tel 手机号
     * @return
     */
    @ApiOperation(value = "generate", notes = "发送短信，获取验证码，tel为手机号")
    @RequestMapping("/generate")
    public Result generate(String tel) throws ExecutionException, InterruptedException {
        String code = codeUtil.generateVerifyCode(4);
        //发送短信
        userService.sendSms(tel, code);
        redisUtils.set(tel, code, 5L, TimeUnit.MINUTES);
        return Result.success("发送成功");
    }

    /**
     * 验证验证码
     *
     * @param key  手机号
     * @param code 验证码
     * @return
     */
    @ApiOperation(value = "verification", notes = "验证验证码，key为手机号，code为验证码")
    @RequestMapping("/verification")
    public Result verification(String key, String code) {
        boolean hasKey = redisUtils.exists(key);
        if (hasKey) {
            Object object = redisUtils.get(key);
            if (code.equals(object.toString())) {
                User user = userService.queryByTel(key);
                if (user != null) {
                    user.setLastTime(new Date());
                    userService.update(user);
                    StpUtil.login(user.getId());
                    boolean falg = StpUtil.isLogin();
                    if (falg) {
                        System.out.println("已登录");
                        //loginId就是用户id StpUtil.login(user.getId())
                        String str = StpUtil.getLoginIdAsString();
                        System.out.println("登录账号：" + str);
                        System.out.println("token:" + StpUtil.getTokenValue());
                        System.out.println(StpUtil.getTokenInfo());
                    } else {
                        System.out.println("未登录");
                    }
                    Map<Object, Object> map = new HashMap<>();
                    map.put("user", user);
                    map.put("token", StpUtil.getTokenValue());
                    return Result.success(map);
                } else {
                    User newUser = new User();
                    newUser.setTel(key);
                    newUser.setUsername(key);
                    newUser.setPassword(key.substring(key.length() - 6));
                    userService.register(newUser);
                    //未注册用户默认注册，用户名为手机号，密码为手机号后六位
                    StpUtil.login(newUser.getId());
                    boolean falg = StpUtil.isLogin();
                    if (falg) {
                        System.out.println("已登录");
                        //loginId就是用户id StpUtil.login(user.getId())
                        String str = StpUtil.getLoginIdAsString();
                        System.out.println("登录账号：" + str);
                        System.out.println("token:" + StpUtil.getTokenValue());
                        System.out.println(StpUtil.getTokenInfo());
                    } else {
                        System.out.println("未登录");
                    }
                    Map<Object, Object> map = new HashMap<>();
                    map.put("user", newUser);
                    map.put("token", StpUtil.getTokenValue());
                    map.put("message", "未注册用户默认注册，用户名为手机号，密码为手机号后六位");
                    return Result.success(map);
                }
            } else {
                return Result.fail("验证码不匹配");
            }
        } else {
            return Result.fail("请注意是否发送短信验证码或验证码已过期");
        }
    }

    @SaCheckRole("admin")
    @ApiOperation(value = "import", notes = "批量导入账号信息")
    @RequestMapping("/import")
    public Result importData(MultipartFile file) throws Exception {
        return userService.importData(file);
    }


    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ApiOperation(value = "login", notes = "登录")
    public Result login(@RequestBody Map<String, String> params) {
        String tel = params.get("tel");
        String password = params.get("password");
        User user = null;
        try {
            user = userService.login(tel, password);
            if (user != null) {
                user.setLastTime(new Date());
                userService.update(user);
            } else {
                return Result.fail("账号或密码错误");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("登录失败");
        }
        StpUtil.login(user.getId());
        boolean falg = StpUtil.isLogin();
        if (falg) {
            System.out.println("已登录");
            //loginId就是用户id StpUtil.login(user.getId())
            String str = StpUtil.getLoginIdAsString();
            System.out.println("登录账号：" + str);
            System.out.println("token:" + StpUtil.getTokenValue());
            System.out.println(StpUtil.getTokenInfo());
        } else {
            System.out.println("未登录");
        }
        Map<Object, Object> map = new HashMap<>();
        map.put("user", user);
        map.put("token", StpUtil.getTokenValue());
        return Result.success(map);

    }


    @RequestMapping("/signOut")
    @ApiOperation(value = "signOut", notes = "退出")
    public Result signOut() {
        StpUtil.logout();
        return Result.success("退出成功");
    }

    @RequestMapping("/isLogin")
    @ApiOperation(value = "isLogin", notes = "判断是否登录")
    public Result isLogin() {
        if (StpUtil.isLogin()) {
            System.out.println("已登录");
        } else {
            System.out.println("请先登录");
        }
        return Result.success(StpUtil.isLogin());
    }

    @RequestMapping("/register")
    @ApiOperation(value = "register", notes = "注册")
    public Result register(@RequestBody User user) {
        //判断该手机号是否注册过
        try {
            if (!this.userService.isRegister(user.getTel())) {
                this.userService.register(user);
            } else {
                return Result.fail("该手机号已注册");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("注册失败");
        }
        return Result.success(user);
    }

    /**
     * 分页查询
     *
     * @param
     * @param
     * @return 查询结果
     */
    @SaCheckRole("admin")
    @RequestMapping("/getAllUsers")
    @ApiOperation(value = "getAllUsers", notes = "获取所有用户")
    public Result getAllUsers(String pageNum, String pageSize) {
        return Result.success(userService.getAllUsers(Integer.parseInt(pageNum), Integer.parseInt(pageSize)));
    }


    @RequestMapping("/countByKey")
    @ApiOperation(value = "countByKey", notes = "通过关键字查询总条数")
    public Result countByKey(String key) {
        int total = 0;
        try {
            total = userService.countByKey(key);
            Map<String, Integer> map = new HashMap<>();
            map.put("total", total);
            return Result.success(map);
        } catch (Exception e) {
            log.info("countByKey");
            log.error(e.toString());
        }
        return Result.fail("查询失败");
    }

    /**
     * 根据id查询单个
     */
    @RequestMapping("/queryById")
    @ApiOperation(value = "queryById", notes = "通过id查询用户")
    public Result queryById(String id) {
        return Result.success(userService.queryById(id));
    }

    /**
     * 模糊查询
     *
     * @param key 关键字
     * @return 单条数据
     */
    @SaCheckRole("admin")
    @RequestMapping("/fuzzyQuery")
    @ApiOperation(value = "fuzzyQuery", notes = "模糊查询")
    public Result fuzzyQuery(String key, String pageNum, String pageSize) {
        List<User> list = new ArrayList<>();
        try {
            list = userService.fuzzyQuery(key, Integer.parseInt(pageNum), Integer.parseInt(pageSize));
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("发生异常");
        }
        return Result.success(list);
    }


    /**
     * 编辑数据
     *
     * @param user 实体
     * @return 编辑结果
     */
    @RequestMapping("/update")
    @ApiOperation(value = "update", notes = "更新用户")
    public Result update(@RequestBody User user) {
        try {
            userService.update(user);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.success("发生异常");
        }
        return Result.success("更新成功");
    }

    @RequestMapping("/changePassword")
    @ApiOperation(value = "changePassword", notes = "修改密码")
    public Result changePassword(@RequestParam("id") String id, @RequestParam("password") String password) {
        try {
            return Result.success(userService.changePassword(id, password));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.fail("修改失败");
    }

    /**
     * 删除数据
     *
     * @param id 主键
     * @return 删除是否成功
     */
    @SaCheckRole("admin")
    @RequestMapping("/deleteById")
    @ApiOperation(value = "deleteById", notes = "通过id删除用户")
    public Result deleteById(String id) {
        try {
            userService.deleteById(id);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.success("发生异常");
        }
        return Result.success("删除成功");
    }

}

